
package com.longrise.android.byjk.app;

import android.annotation.TargetApi;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.multidex.MultiDex;

import com.alibaba.android.arouter.launcher.ARouter;
import com.longrise.android.byjk.BuildConfig;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.errorlog.UncaughtException;
import com.longrise.common.baseapp.BaseAppLike;
import com.longrise.common.datasource.local.sp.CacheUtils;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.AppUtil;
import com.longrise.common.utils.DZZWTools;
import com.longrise.common.utils.FolderConstants;
import com.longrise.common.utils.PrintLog;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.smtt.sdk.QbSdk;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;


/**
 * Created by callxkj on 2017/3/22.
 * applicationlike类
 */

public class BYJKAppLike extends BaseAppLike {

    private static final String TAG = "BaseAppLike";
    private static Application mAPP;
    public static IWXAPI mIWXAPI;

    public BYJKAppLike(Application application, int tinkerFlags,
                       boolean tinkerLoadVerifyFlag, long applicationStartElapsedTime,
                       long applicationStartMillisTime, Intent tinkerResultIntent) {
        super(application, tinkerFlags, tinkerLoadVerifyFlag,
                applicationStartElapsedTime, applicationStartMillisTime, tinkerResultIntent);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mAPP = getApplication();
        initExceptionCaught();
        initLoadManager();
        initPrintLog();
        initUmeng();
        registerWXAPI();
        initImageLoader();
        registerBroadCast();
        initBugly();
        initARouter();
        initX5();
    }

    /**
     * 获取application 对象
     */
    public static Application getAPP() {
        return mAPP;
    }

    /**
     * 打印日子的工具类 初始化
     */
    private void initPrintLog() {
        if (BuildConfig.DEBUG) {
            PrintLog.setStatus(PrintLog.LEVEL_ERROR);
        } else {
            PrintLog.setStatus(PrintLog.LEVEL_NONE);
        }
    }

    /**
     * 初始化友盟 分享 统计
     */
    private void initUmeng() {
        PlatformConfig.setWeixin("wx6f836b4acd094bd1", "710b586b974840c82deebe516deb4b64");
        PlatformConfig.setQQZone("1106475095", "syNPopFtczk1hxlG");
        //如需要使用AndroidManifest.xml中配置好的appkey和channel值，UMConfigure.init调用中appkey和channel参数请置为null
        UMConfigure.init(mAPP, UMConfigure.DEVICE_TYPE_PHONE, null);

        // 新增secret Key接口,防止appkey被盗用,secretkey网站申请
        // MobclickAgent.setSecret(Context context, String secretkey)

        //场景类型设置接口  EScenarioType.E_UM_NORMAL 普通统计场景类型 ;; EScenarioType.E_UM_GAME 游戏场景类型
        MobclickAgent.setScenarioType(mAPP, MobclickAgent.EScenarioType.E_UM_NORMAL);

        //禁止默认的页面统计方式
        MobclickAgent.openActivityDurationTrack(false);
        if (BuildConfig.DEBUG) {
            //开启ShareSDK debug模式，方便定位错误，具体错误检查方式可以查看
            //http://dev.umeng.com/social/android/quick-integration的报错必看，正式发布，请关闭该模式
            Config.DEBUG = true;
            UMConfigure.setLogEnabled(true);

        } else {
            Config.DEBUG = false;
            UMConfigure.setLogEnabled(false);
        }

    }


    private void registerWXAPI() {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        mIWXAPI = WXAPIFactory.createWXAPI(mAPP.getApplicationContext(), UserInfor.getInstance().APP_ID, true);
        boolean registerApp = mIWXAPI.registerApp(UserInfor.getInstance().APP_ID);
        PrintLog.d(TAG, registerApp + "");
    }


    private void initImageLoader() {
        //创建默认的ImageLoader配置参数
        ImageLoaderConfiguration configuration = ImageLoaderConfiguration
                .createDefault(mAPP.getApplicationContext());

        //Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(configuration);
    }


    /**
     * 网络异常的广播 loaddatamanager里面发出
     */
    private void registerBroadCast() {
        BBnetworkBroadCast broadCast = new BBnetworkBroadCast();
        IntentFilter filter = new IntentFilter();
        filter.addAction("nonetwork");
        mAPP.registerReceiver(broadCast, filter);
    }


    /**
     * 无网络广播
     */
    class BBnetworkBroadCast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            DZZWTools.showToast(mAPP.getApplicationContext(), mAPP.getString(R.string.nonetwork), 2 * 1000);
        }
    }

    /**
     * 新的网络加载类的初始化
     */
    private void initLoadManager() {
        int appVersionCode = AppUtil.getAppVersionCode();
        LoadDataManager.getInstance().init(String.valueOf(appVersionCode));
        //设置Session超时再次登录成功实现类的完整路径

        LoadDataManager.getInstance().setReloginPath("com.longrise.common.datasource.remote.ReloginUtil");
    }


    /**
     * 初始化bugly
     * 自动在release版本配置bugly
     */
    private void initBugly() {
        if (BuildConfig.DEBUG) {
            // 设置开发设备，默认为false，上传补丁如果下发范围指定为“开发设备”，需要调用此接口来标识开发设备
            Bugly.setIsDevelopmentDevice(getApplication(), true);
            Bugly.init(getApplication(), "026d73e8f2", true);
        } else {
            // 设置开发设备，默认为false，上传补丁如果下发范围指定为“开发设备”，需要调用此接口来标识开发设备
            Bugly.setIsDevelopmentDevice(getApplication(), false);
            CrashReport.initCrashReport(mAPP.getApplicationContext(), "026d73e8f2", false);
            Bugly.init(getApplication(), "026d73e8f2", false);
        }
    }

    // -------------------bugly--------start----------------------
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    public void onBaseContextAttached(Context base) {
        super.onBaseContextAttached(base);
        // you must install multiDex whatever tinker is installed!
        MultiDex.install(base);

        // 安装tinker
        // TinkerManager.installTinker(this); 替换成下面Bugly提供的方法
        Beta.installTinker(this);
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void registerActivityLifecycleCallback(Application.ActivityLifecycleCallbacks callbacks) {
        getApplication().registerActivityLifecycleCallbacks(callbacks);
    }
    // -------------------bugly--------end----------------------

    /**
     * 初始化跳转工具 arouter
     */
    private void initARouter() {
        if (BuildConfig.DEBUG) {
            ARouter.openLog();
            ARouter.openDebug();
        }
        ARouter.init(mAPP);
    }

    /**
     * 异常日志捕捉然后保存本地
     */
    private void initExceptionCaught() {
        //程序崩溃信息记录，在/baoa_error/log/目录下  条件异常退出google 分析日志
        UncaughtException mUncaughtException = UncaughtException.getInstance();
        mUncaughtException.init(getAPP(), FolderConstants.CACHE_DIR + "/system/log/", new UncaughtException.OnExceptionEvent() {
            @Override
            public void onExecption(String excepiton) {
                //如果开发者调用kill或者exit之类的方法杀死进程，
                // 请务必在此之前调用onKillProcess(Context context)方法，用来保存统计数据。
                MobclickAgent.onKillProcess(getAPP());
            }
        });
    }

    /**
     * 初始化腾讯X5内核
     */
    private void initX5(){
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                PrintLog.d("app", " onViewInitFinished is " + arg0);
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(getAPP(),  cb);
    }
}
